package com.ruoyi.system.service.impl;

import com.ruoyi.system.service.FileStorageService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Service
public class LocalFileStorageService implements FileStorageService {

    @Value("${file.storage.package}")
    private String storagePath;
    private Path basePath;
    
    @PostConstruct
    public void init() {
        this.basePath = Paths.get(storagePath).toAbsolutePath().normalize();
        ensureDirectoryExists();
    }
    
    private void ensureDirectoryExists() {
        try {
            if (!Files.exists(basePath)) {
                Files.createDirectories(basePath);
            }
        } catch (Exception e) {
            throw new RuntimeException("无法创建存储目录: " + basePath, e);
        }
    }
    
    @Override
    public InputStream getFileInputStream(String filePath) throws IOException {
        Path file = buildAndValidateFilePath(filePath);
        return Files.newInputStream(file);
    }
    
    @Override
    public long getFileSize(String filePath) throws IOException {
        Path file = buildAndValidateFilePath(filePath);
        return Files.size(file);
    }
    
    @Override
    public boolean fileExists(String filePath)   {
        Path file = buildAndValidateFilePath(filePath);
        return Files.exists(file) && Files.isRegularFile(file);
    }
    
    @Override
    public long getLastModified(String filePath) throws IOException {
        Path file = buildAndValidateFilePath(filePath);
        return Files.getLastModifiedTime(file).toMillis();
    }
    
    private Path buildAndValidateFilePath(String fileName)  {
        if (fileName == null || fileName.trim().isEmpty()) {
            throw new IllegalArgumentException("文件名不能为空");
        }
        
        // 如果已经是绝对路径，直接使用
        if (fileName.contains(":") || fileName.startsWith("/")) {
            Path absolutePath = Paths.get(fileName).toAbsolutePath().normalize();
            // 可选：检查是否在允许的目录范围内
            if (!absolutePath.startsWith(basePath)) {
            }
            return absolutePath;
        }
        
        // 相对路径，基于配置的存储目录
        Path targetFile = basePath.resolve(fileName).normalize();
        
        // 安全检查
        if (!targetFile.startsWith(basePath)) {
            throw new SecurityException("非法文件路径访问");
        }
        
        return targetFile;
    }
    
    /**
     * 获取存储目录路径（用于日志和调试）
     */
    public String getStoragePath() {
        return basePath.toString();
    }
}